package com.example.rotateimageview.rotateImage

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.DecelerateInterpolator
import android.widget.FrameLayout

/**
 * author  : Liushuai
 * time    : 2021/8/29 11:34
 * desc    :
 */
class RotateViewAnimationLayout @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : FrameLayout(context, attributeSet, 0) {
    private var firstAnimation: Animation = RotateImageAnimation(0f, 90f)
    private var secondAnimation: Animation = RotateImageAnimation(90f, 180f)

    private var currentShowIndex = 0
    private val MAX_SHOW_COUNT = 2

    private var currentDegrees=0

    init {
        firstAnimation.fillBefore = true
        firstAnimation.duration = 300
        firstAnimation.interpolator = AccelerateInterpolator()
        secondAnimation.fillAfter = true
        secondAnimation.duration = 300
        secondAnimation.interpolator = DecelerateInterpolator()

    }


    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            startRotateAnimation()
            startRotateTask()
        }
    }

    fun startRotateTask() {
        handler.sendEmptyMessageDelayed(0, 3000)
    }


    private fun startRotateAnimation() {
        firstAnimation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation?) {

            }

            override fun onAnimationEnd(animation: Animation?) {
                getChildAt(currentShowIndex).visibility = View.GONE
                currentShowIndex++
                if (currentShowIndex >= MAX_SHOW_COUNT) {
                    currentShowIndex = 0
                }
                getChildAt(currentShowIndex).visibility = View.VISIBLE
                startAnimation(secondAnimation)
            }

            override fun onAnimationRepeat(animation: Animation?) {
            }
        })
        startAnimation(firstAnimation)
    }

    /**
     * 镜像效果
     */
    private fun restoreChildView(view: View) {
        view.scaleX = -1f
    }


    override fun onDetachedFromWindow() {
        handler.removeCallbacksAndMessages(null)
        super.onDetachedFromWindow()
    }

}